﻿using Newtonsoft.Json;
using BaoShouTangServer.DTOModel;
using BaoShouTangServer.Models;
using BaoShouTangServer.Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BaoShouTangServer.Controllers
{
    public class PDAController : Controller
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        // GET: PDA
        [HttpPost]
        public ActionResult SendMessage(MessageDTO messageDTO)
        {
            Logger.Warn("接受到的：" + JsonConvert.SerializeObject(messageDTO));
            HttpData<object> httpData = SendWeChatWithImage(messageDTO);
            return Json(httpData);

        }

        public static HttpData<object> SendWeChatWithImage(MessageDTO messageDTO)
        {
            
            HttpData<object> httpData = new HttpData<object>();
            try
            {
                string corpid = ConfigurationManager.AppSettings["corpid"].ToString();
                string corpsecret = ConfigurationManager.AppSettings["corpsecret"].ToString();
                
                string tokenurl = $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}";
                Dictionary<string, string> dicToken = HttpHelper.HttpGet<Dictionary<string, string>>(tokenurl);
                string token = dicToken["access_token"];

                string imgurl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + "&type=image";
                string mesgurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token;
                string imgResponse = "";
                if (messageDTO.接受格式 == "图片")
                {
                    //byte[] a = BytesToHexString(messageDTO.接受内容);
                    imgResponse = HttpHelper.HttpPost("工票", messageDTO.图片, imgurl);
                    Dictionary<string, string> dicImgResponse = JsonExtends.ToEntity<Dictionary<string, string>>(imgResponse);
                    string mediaId = dicImgResponse["media_id"];
                   
                    WeChatImage weChatImage = new WeChatImage();
                    //发给开发者自己以及管理员
                    string orgtouser = ConfigurationManager.AppSettings["orgtouser"].ToString();
                    //weChatImage.touser = "447275103@qq.com|baij45";
                    weChatImage.touser = orgtouser + "|" + messageDTO.接受账号;
                    weChatImage.msgtype = "image";
                    weChatImage.agentid = 1000002;
                    weChatImage.image = new Image { media_id = mediaId };
                    // weChatImage.text = new Text { content = mesg };
                    //发送二维码图片
                    string QRCodeResponse = HttpHelper.HttpPost(mesgurl, JsonExtends.ToJson(weChatImage));
                    Dictionary<string, string> dicQRCodeResponse = JsonExtends.ToEntity<Dictionary<string, string>>(QRCodeResponse);
                    httpData.code = 200;
                    httpData.msg = dicQRCodeResponse["errmsg"];
                    Logger.Warn("发送图片返回值："+ httpData.msg);
                }
                else
                {
                    //发送信息
                    WeChatImage weChatImage = new WeChatImage();
                    //发给开发者自己以及管理员
                    string orgtouser = ConfigurationManager.AppSettings["orgtouser"].ToString();
                    weChatImage.touser = orgtouser + "|" + messageDTO.接受账号;
                    string mesg = messageDTO.接受内容;
                    weChatImage.msgtype = "text";
                    weChatImage.agentid = 1000002;
                    weChatImage.text = new Text { content = mesg };
                    string TextResponse = HttpHelper.HttpPost(mesgurl, JsonExtends.ToJson(weChatImage));
                    Dictionary<string, string> dicTextResponse = JsonExtends.ToEntity<Dictionary<string, string>>(TextResponse);
                    httpData.code = 200;
                    httpData.msg = dicTextResponse["errmsg"];
                    Logger.Warn("发送文本返回值：" + httpData.msg);
                }
               
            }
            catch (Exception e)
            {
                httpData.code = 0;
                httpData.msg = e.Message;
            }
            return httpData;
        }
        public static byte[] BytesToHexString(string hexString)
        {
            hexString = hexString.Replace("0x","");
            // 将16进制秘钥转成字节数组
            byte[] bytes = new byte[hexString.Length / 2];
            for (var x = 0; x < bytes.Length; x++)
            {
                var i = Convert.ToInt32(hexString.Substring(x * 2, 2), 16);
                bytes[x] = (byte)i;
            }
            return bytes;
        }
    }
}